package com.allwees.support.fileservice.req;

import com.allwees.core.common.util.encrypt.MD5Util;
import com.allwees.support.fileservice.FileException;
import com.allwees.support.fileservice.upload.AliossBucketEnum;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

@Data
public class UploadFileReq {

    /** 上传的文件 **/
    private MultipartFile filedata;

    /** 文件名 **/
    private String filename;

    /** 文件说明 **/
    private String description;

    /** 上传的文件 **/
    private String typeCode;

    /** 是否图片 **/
    private Boolean isImage;

    /** 上传的文件 **/
    private Long time;

    /** 签名 **/
    private String signature;

    public void validate(boolean validateSignature) {
        if(validateSignature){
            validateSignature();
        }
        validateTypeCode();
    }

    public void validateSignature() {
        if(StringUtils.isBlank(signature)) {
            throw new FileException("签名错误");
        }
        if (!signature.equalsIgnoreCase(MD5Util.digest(StringUtils.join(new Object[]{filename, typeCode, filedata.getSize(), time}, "_F_")))) {
            throw new FileException("签名错误");
        }
    }

    public void validateTypeCode() {
        if (StringUtils.isBlank(typeCode)) {
            throw new FileException("未匹配配置的bucket: " + typeCode);
        }

        AliossBucketEnum bucketEnum = AliossBucketEnum.getEnum(typeCode);
        if (bucketEnum == null) {
            throw new FileException("未匹配配置的bucket: " + typeCode);
        }
    }
}
